<?php
namespace tp5_lib\wxwork\logic;
/**
 * 接收企业微信用户对APP发送的消息
 * 自动应答
 * 主动发送消息
 */
class Message extends WXWork
{
    public $userID;//正在对话的用户ID
    public $_crypt;//加密解密用的对象
    public function __get($name)
    {
        if($name==="crypt"){
            if(!$this->_crypt){
                vendor('wxwork.WXBizMsgCrypt');
                $token=config("wxwork_message_token");
                $key=config("wxwork_message_key");
                $this->_crypt=new \WXBizMsgCrypt($token, $key, $this->corpID);
            }
            return $this->_crypt;
        }
    }
    /**
     * 主动向用户发送消息
     * @param array to 关联数组
     */
    public function makeSendTarget($user=[],$department=[],$tag=[])
    {
        $target=[];
        if($user){
            $target["touser"]=is_array($user) ? implode("|",$user) : $user;
        }
        if($user){
            $target["toparty"]=is_array($department) ? implode("|",$department) : $department;
        }
        if($user){
            $target["totag"]=is_array($tag) ? implode("|",$tag) : $tag;
        }
        if(!$target){
            $target["touser"]="@all";
        }
        return $target;
    }
    public function makeTextMessage($content)
    {
        $message=[
            "msgtype"=>"text",
            "text"=>[
                "content"=>$content
            ],
        ];
        return $message;
    }
    public function makeTextCardMessage($title,$description,$url,$btntxt="")
    {
        $message=[
            "msgtype"=>"textcard",
            "textcard"=>[
                "title"=>$title,
                "description"=>$description,
                "url"=>$url,
                "btntxt"=>$btntxt
            ],
        ];
        return $message;
    }
    public function send($agentid,$target,$message,$safe=0){
        $url=$this->host."message/send?access_token=".$this->getToken();
        $data=[
            "agentid"=>$agentid,
            "safe"=>$safe
        ];
        $data=array_merge($data,$target,$message);
        $response=$this->post($url,$data);
        return $response;

    }
    //用来向企业微信服务器证明这个服务器有效的接口
    //验证的时候，需要调用testify方法，验证成功后就改成receive方法
    public function testify(){
        $signature = $_GET["msg_signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $echostr=$_GET["echostr"];
        $echostr = str_replace(" ","+",$echostr);
        $echostr = str_replace("\/","/",$echostr);
        $message = "";
        $errCode = $this->crypt->VerifyURL($signature, $timestamp, $nonce, $echostr, $message);
        if ($errCode == 0) {
            echo $message;
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
        exit;
    }
    //用来接受消息的接口
    public function receive(){
        $signature = $_GET["msg_signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $data = file_get_contents("php://input");
        $decrypted = "";
        $errCode = $this->crypt->DecryptMsg($signature, $timestamp, $nonce, $data, $decrypted);
        if ($errCode == 0) {
            $xml = new \DOMDocument();
            $xml->loadXML($decrypted);
            $this->userID=$xml->getElementsByTagName('FromUserName')->item(0)->nodeValue;
            $this->agentID=$xml->getElementsByTagName('AgentID')->item(0)->nodeValue;
            $message=$xml->getElementsByTagName('Content')->item(0)->nodeValue;
            return $message;
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
    }
    //被动回复消息
    public function reply($message){
        $timestamp=time();
        $nonce=rand(100000,999999);
        $data = '<xml>
            <ToUserName><![CDATA['.$this->userID.']]></ToUserName>
            <FromUserName><![CDATA['.$this->corpID.']]></FromUserName>
            <CreateTime>'.$timestamp.'</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA['.$message.']]></Content>
            <MsgId>1234567890123456</MsgId>
            <AgentID>'.$this->agentID.'</AgentID>
        </xml>';
        $encrypted = ""; //xml格式的密文
        $errCode = $this->crypt->EncryptMsg($data, $timestamp, $nonce, $encrypted);
        if ($errCode == 0) {
            echo $encrypted;
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
        exit;
    }
}
